﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Common.Model;
using Newtonsoft.Json.Linq;

namespace Spider.Spider
{
    class RtnHotList
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(RtnHotList));

        public static List<HotList> GetListAll(string date)
        {          
            List<HotList> templist = new List<HotList>();
            List<HotList> templist_cyb = RtnSzse("http://www.szse.cn/szseWeb/common/szse/files/text/nmTxt/gk/nm_jy", date);
            if (templist_cyb == null)
            {               
                Log.Info(date+"龙虎榜数据未出或异常");
                return null;
            }
            List<HotList> templist_zxb = RtnSzse("http://www.szse.cn/szseWeb/common/szse/files/text/smeTxt/gk/sme_jy", date);
            List<HotList> templist_zb = RtnSzse("http://www.szse.cn/szseWeb/common/szse/files/text/jy/jy", date);
            List<HotList> templist_Sh = RtnSse(date);
            if (templist_zxb != null && templist_zxb != null && templist_Sh != null)
            {
                templist.AddRange(templist_zxb);
                templist.AddRange(templist_zb);
                templist.AddRange(templist_Sh);
                var xx = ToDataTable(templist_Sh);
                Log.Info(date+"龙虎榜数据已经更新");
                return templist;
            }
            return null;
        }
        public static DataTable ToDataTable<T>(IEnumerable<T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }
        public static  List<HotList> RtnSzse(string urle,string date)
        {
            //string url= "http://www.szse.cn/szseWeb/common/szse/files/text/nmTxt/gk/nm_jy"+ date.Substring(2,6) +
            //".txt";
            string url = urle + date.Substring(2, 6) +
                         ".txt";
            var rtnszse = GetSZSE(url);
            if (rtnszse.Contains("您访问的页面不存在或有异常")) return null;
            String[] ss = rtnszse.Replace("\r","").Split('\n');
            bool startpoint = false;
            string typedetails = string.Empty;
            string stkcode=string.Empty;
            string stkname=string.Empty;
            string direction=string.Empty;
            List<HotList> templist = new List<HotList>();
            for (int i = 0; i < ss.Length; i++)
            {
                if (ss[i].Contains("详细信息"))
                {
                    startpoint = true;
                    continue;
                }
                if (startpoint == false) continue;
                if (ss[i].Contains("："))
                {
                    typedetails = ss[i].Replace("：", "");
                    continue;
                }
                if (ss[i].Contains("(代码"))
                {
                    string[] temp = ss[i].Split('(');
                    stkname = temp[0];
                    stkcode = temp[1].Substring(2, 6);
                    continue;
                }
                if (ss[i].StartsWith("买入金额最大"))
                {
                    direction = "买入";
                    continue;
                }
                if (ss[i].StartsWith("卖出金额最大"))
                {
                    direction = "卖出";
                    continue;
                }
                if (ss[i].StartsWith("营业部或交易")|| ss[i].StartsWith("异常期间") || ss[i].StartsWith("-")|| ss[i].Length < 2||ss[i].EndsWith("，"))
                {
                    continue;
                }
                string[] str = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(ss[i], " ").Split(' ');



                templist.Add(new HotList
                {
                    SecCode = stkcode,
                    SecName = stkname,
                    Date = date,
                    DepartmentName = str[0],
                    BuyAmount = System.Convert.ToDouble(str[1]),
                    SellAmount = System.Convert.ToDouble(str[2]),
                    Direction = direction,
                    Type = RtnType(typedetails),
                    TypeDetails = typedetails

                });

            }
            return  templist;
        }
        static public List<HotList> RtnSse(string date)
        {
            string ssedate = date.Substring(0, 4)+"-"+ date.Substring(4, 2) + "-"+ date.Substring(6, 2);
            string strrtn = "";
            var xx = GetSSE("http://query.sse.com.cn/infodisplay/showTradePublicFile.do?dateTx="+ ssedate);
            var fileinfo = JObject.Parse(xx);
            if (fileinfo["fileContents"].ToString() != "")
            {
                foreach (var temp in fileinfo["fileContents"])
                {
                    strrtn = strrtn + temp + "\n";
                }
            }
            else return null;
            String[] ss = strrtn.Split('\n');
            bool startpoint = false;
            bool canwrite = false;
            string type = string.Empty;
            string typedetails = string.Empty;
            string stkcode = string.Empty;
            string stkname = string.Empty;
            string direction = string.Empty;
            List<HotList> templist = new List<HotList>();
            for (int i = 0; i < ss.Length; i++)
            {
                if (ss[i].Contains("、"))
                {
                    if(ss[i].Contains(":"))
                    { 
                        startpoint = true;
                        typedetails = Search_string(ss[i], "、",":");
                        continue;
                    }
                    canwrite = false;
                    continue;
                }
                if (startpoint == false) continue;
                if (ss[i].Contains("证券代码: "))
                {
                    string[] temp = ss[i].Split(':');
                    stkname = temp[2];
                    stkcode = temp[1].Substring(1, 6);
                    canwrite = true;
                    continue;
                }
                if (canwrite == false) continue;
                if (ss[i].Contains("买入金额"))
                {
                    direction = "买入";
                    continue;
                }
                if (ss[i].Contains("卖出金额"))
                {
                    direction = "卖出";
                    continue;
                }
                if (ss[i].StartsWith("      ") ||  ss[i].Length < 2 )
                {
                    continue;
                }
                string[] str = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(ss[i], " ").Split(' ');


                double amount = 0;
                if (!double.TryParse(str[3], out amount))
                {
                    str[2] = str[2] + str[3];
                    str[3] = str[4];
                }
                if (str[3].Contains("%")) continue;

                templist.Add(new HotList
                {
                    SecCode = stkcode,
                    SecName = stkname,
                    Date = date,
                    DepartmentName = str[2],
                    BuyAmount = direction=="买入"?System.Convert.ToDouble(str[3]):0,
                    SellAmount = direction == "买入" ? 0:System.Convert.ToDouble(str[3]),
                    Direction = direction,
                    Type = RtnType(typedetails),
                    TypeDetails =typedetails
                    
                });

            }
            return templist;
        }
        static private string GetSZSE(string strURL)
        {
            HttpWebRequest request;
            // 创建一个HTTP请求
            request = (HttpWebRequest)WebRequest.Create(strURL);
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
            string responseText = myreader.ReadToEnd();
            myreader.Close();
            return responseText;
        }
        static public string GetSSE(string strURL)
        {
            HttpWebRequest request;
            // 创建一个HTTP请求
            request = (HttpWebRequest)WebRequest.Create(strURL);
            request.Host = "query.sse.com.cn";
            request.Referer = "http://www.sse.com.cn/disclosure/diclosure/public/";
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            string responseText = myreader.ReadToEnd();
            myreader.Close();
            return responseText;
        }
        public static string Search_string(string s, string s1, string s2)  //获取搜索到的数目  
        {  
            int n1, n2;  
            n1 = s.IndexOf(s1, 0) + s1.Length;   //开始位置  
            n2 = s.IndexOf(s2, n1);               //结束位置  
            return s.Substring(n1, n2 - n1);   //取搜索的条数，用结束的位置-开始的位置,并返回  
        }
        public static int RtnType(string type)
        {
            if (type.Contains("涨幅偏离值达到7%")) return 1;
            if (type.Contains("跌幅偏离值达到7%")) return 2;
            if (type.Contains("达到15%")) return 3;
            if (type.Contains("日换手率达到20%")) return 4;
            if (type.Contains("无价格涨跌幅限制")) return 5;
            if (type.Contains("涨幅偏离值累计达到20%")) return 6;
            if (type.Contains("跌幅偏离值累计达到20%")) return 7;
            if (type.Contains("涨幅偏离值累计达到15%")) return 8;
            if (type.Contains("跌幅偏离值累计达到15%")) return 9;
            if (type.Contains("涨幅偏离值累计达到12%")) return 22;
            if (type.Contains("跌幅偏离值累计达到12%")) return 23;
            if (type.Contains("日均换手率")) return 10;
            if (type.Contains("当日无价格涨跌幅限制的A股，出现异常波动停牌的")) return 11;
            if (type.Contains("当日无价格涨跌幅限制的B股，出现异常波动停牌的")) return 12;
            if (type.Contains("连续2个交易日触及涨幅限制，同一营业部净买入股数占当日总成交股数30%以上，且上市公司未有重大事项公告")) return 13;
            if (type.Contains("连续2个交易日触及跌幅限制，同一营业部净卖出股数占当日总成交股数30%以上，且上市公司未有重大事项公告")) return 14;
            if (type.Contains("ST、*ST、S证券连续三个交易日涨停")) return 15;
            if (type.Contains("ST、*ST、S证券连续三个交易日跌停")) return 16;
            if (type.Contains("单只标的证券的当日融资买入数量达到当日该证券总交易量的50%以上")) return 17;
            if (type.Contains("单只标的证券的当日融券卖出数量达到当日该证券总交易量的50%以上")) return 18;
            if (type.Contains("风险警示股票盘中换手率达到或超过30%")) return 19;
            if (type.Contains("退市整理")) return 20;
            if (type.Contains("实施特别停牌")) return 21;
            return 0;
        }
    }
}